package pdn.sci.cs.action;

import org.springframework.beans.factory.annotation.Autowired;

import pdn.sci.cs.entity.SessionKey;
import pdn.sci.cs.entity.SystemUser;
import pdn.sci.cs.service.SystemUserService;

public class UserAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private String username;
	private String password;
	private String search;

	private SystemUser systemUser;

	@Autowired private SystemUserService systemUserService;

	public String index() {
		return SUCCESS;
	}

	public String signIn() {

		validateSignIn();
		if (hasErrors()) {
			return INPUT;
		} else {
			systemUser = systemUserService.signIn(username, password);
			if (systemUser == null) {
				addActionError("Invalid username and/or password");
				return INPUT;
			} else {
				if (session != null) {
					session.put(SessionKey.USER_TYPE, systemUser.getUserRole());
					session.put(SessionKey.SESSION_USER, systemUser);
					return SUCCESS;
				} else {
					addActionError("Session has been expired");
					return INPUT;
				}
			}
		}
	}

	private void validateSignIn() {
		if (username == null || username.isEmpty()) {
			addFieldError("username", "Username cannot be empty");
		}

		if (password == null || password.isEmpty()) {
			addFieldError("password", "Password cannot be empty");
		}
	}

	public String userLogin() {
		System.out.println("Username " + username);
		System.out.println("Password " + password);

		if (username != null && username.trim().length() != 0) {
			return SUCCESS;
		} else {
			return INPUT;
		}
	}
	
	public String home() {
		return SUCCESS;
	}

	public String searchUser() {
		System.out.println("Search Key : " + search);

		return SUCCESS;
	}
	
	public String addMember(){
		return SUCCESS;
	}

	public String searchInit() {
		search = "Vajira";
		return SUCCESS;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

}
